<template>
  <div class="box-container">
    <!-- 搜索 -->
     <div class="top-main">
    <el-form class="top-form-fl" :model="queryParams" ref="queryRef" label-width="auto" :inline="true">
      <el-form-item label="权限名称:" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入权限名称" clearable/>
      </el-form-item>
      <el-form-item label="状态:" prop="states">
        <el-select v-model="queryParams.states" placeholder="选择状态">
          <el-option v-for="item in statesOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建日期:" prop="beginTime" style="width: 400px;">
        <el-col :span="11">
          <el-date-picker v-model="queryParams.beginTime" type="date" placeholder="开始日期" style="width: 100%" />
        </el-col>
        <el-col :span="2" class="text-center">
          <span class="text-gray-500">-</span>
        </el-col>
        <el-col :span="11">
          <el-date-picker v-model="queryParams.endTime" type="date" placeholder="结束日期" style="width: 100%" />
        </el-col>
      </el-form-item>
      <el-form-item label="所属公司名称:" prop="companyName">
        <el-input v-model="queryParams.companyName" placeholder="请输入所属公司名称" clearable/>
      </el-form-item>
    </el-form>
     <div class="top-from-fr">
          <el-button class="top-Search" @click="getFilterData" type="primary">搜索</el-button>
          <el-button class="top-Refresh" @click="resetFrome">重置</el-button>
      </div>   
      </div>
    <el-button type="primary" :icon="Plus" style="float:right;margin: 20px;"
      @click="addPermissionRoleDialog">新增</el-button>

    <Table v-bind="tableData" @editPermissions="editPermissions" @deleteBox="deleteBox" @handleSwitch="handleSwitch"
      @pageChange="pageChange">
    </Table>

    <!-- 新增权限角色弹窗 -->
    <el-dialog v-model="dialogUserRole" :title="typeOpen==1 ? '新增权限':'编辑权限'" width="400px"  @close="cancel">
      <el-form :model="form" :rules="rules" ref="rolesRef" label-width="80px">
         <el-form-item label="权限名称" prop="permissionName">
                     <el-input v-model="form.permissionName" placeholder="请输入名称" />
            </el-form-item>
             <el-form-item label="所属公司" prop="companyId">
                    <el-select v-model="form.companyId" placeholder="请选择公司">
                      <el-option v-for="(item, index) in companyNameList" :key="index" :label="item.name" :value="item.id" />
                    </el-select>
            </el-form-item>
             <el-form-item label="权限菜单" prop="permissionName">
                  <el-tree
                      :data="menuOptions"
                      show-checkbox
                      ref="menuRef"
                      :check-strictly="true"
                      node-key="id"
                        @check-change="handleCheckChange"
                      :props="{ label: 'name', children: 'children' }"
                  ></el-tree>
            </el-form-item>
        </el-form>
         <template #footer>
            <div class="dialog-footer">
               <el-button type="primary" @click="submitForm(rolesRef)">确 定</el-button>
               <el-button @click="cancel">取 消</el-button>
            </div>
         </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onActivated ,nextTick} from 'vue'
import Table from '@/views/components/table/index.vue';
import { menusList } from '@/api/systemManage/menu/index'
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus } from '@element-plus/icons-vue'
import { getCompanyList, getRolesPage, UpdatePermissions, getRoleMenuList, deleteRole, updateRoleStatus, addRole, getRolePermissions, getRoleDetailById, updateRolePermissions } from '@/api/systemManage/rights/index'
import { config } from 'process';
import { el, it } from 'element-plus/es/locale/index.mjs';
import { handleTree } from '@/utils/ruoyi'
import type { FormInstance, FormRules } from 'element-plus'
const statesOptions=ref([
    {
      value: '1',
      label: '启用',
    },
    {
      value: '0',
      label: '停用',
    }
  ]
)
const queryRef=ref(null)
const companyNameList=ref([])
const dialogUserRole=ref(false) //弹框
const rolesRef=ref()

const menuTree = ref([]);
const menuRef=ref([])
const isRendering = ref(false);

const data = reactive({
  form: {},
  queryParams: {
    name: '',
    states:'',
    beginTime: '',
    endTime: '',
    companyName:'',
    pageNum: 1,
    pageSize: 10,
  },
  rules: {
    permissionName: [{ required: true, message: "权限名称不能为空", trigger: "blur" }],
    companyId: [{ required: true, message: "请选择所属公司", trigger: "blur" }],
  }
});
const { queryParams, form, rules } = toRefs(data);
onActivated(() => {
  getFilterData()
  getGsList()
   getMenuList() 
})
// 基础数据
const tableData = reactive({
  header: [
    { key: 'name', colWidth: '60', title: '权限名称', type: 'name', isCheck: true },
    { key: 'roleMenuSimpleList', colWidth: '240', title: '权限菜单', type: 'roleMenuSimpleList', isCheck: true },
    { key: 'companyName', colWidth: '140', title: '所属公司名称', type: 'companyName', isCheck: true },
    { key: 'status', colWidth: '40', title: '状态', type: 'status', isCheck: true },
    { key: 'createTime', colWidth: '80', title: '创建日期', type: 'createTime', isCheck: true },
    {
      key: 'operate',
      colWidth: '60',
      title: '操作',
      type: 'operate',
      isCheck: true,
      buttons: [
        {
          icon: 'Edit',
          type: 0,  //企业用户 1  企业账号 0 
          status: "1",
          command: 'editPermissions',
          content: '',
        },
        {
          icon: 'Open',
          type: 0,  //企业用户 1  企业账号 0 
          status: "1",
          command: 'handleSwitch',
          content: '',
        },
        {
          icon: 'Delete',
          type: 0,  //企业用户 1  企业账号 0 
          command: 'deleteBox',
          content: '',
        }
      ]
    }
  ],
  data: [],
  config: {
    isSelection: false,
    isList: false,
    isPagination: true, // 是否分页
    total: 0, // 总条数
    loading: false,
    isRealName: false, // 是否已经实名认证
  }
})
// 重置搜索数据
const resetFrome = () => {
  queryRef.value.resetFields()
  queryParams.value.beginTime=''
  queryParams.value.endTime=''
}
// 搜索数据
const getFilterData = () => {
  getRolesPage(JSON.stringify(queryParams.value)).then(res => {
    tableData.data = res.data.list.sort((a, b) => a.sort - b.sort)
    tableData.config.total = res.data.total
    console.log(res)
  })
}
const getGsList=()=>{
    getCompanyList().then(res => {
      companyNameList.value = res.data
    })
}
//父子不关联
const checkAllChildren = (node, checked) => {
    if (node.children) {
      node.children.forEach(child => {
        menuRef.value.setChecked(child.id, checked, false);
        checkAllChildren(child, checked);
      });
    }
  };

  const findParent = (id, nodes) => {
    for (let node of nodes) {
      if (node.children) {
        for (let child of node.children) {
          if (child.id === id) {
            return node;
          }
          const parent = findParent(id, node.children);
          if (parent) {
            return parent;
          }
        }
      }
    }
    return null;
  };

const handleCheckChange = (node, checked) => {
    if (isRendering.value) {
      return;
    }

    if (checked === false) {
      // 子节点，取消选中
      checkAllChildren(node, false);
    } else {
      //否则(为选中状态)

      // 子节点，选中
      checkAllChildren(node, true);

      // 若有父节点，选中
      isRendering.value = true;
      let parent = findParent(node.id, menuTree.value);
      while (parent) {
        menuRef.value.setChecked(parent.id, true, false);
        parent = findParent(parent.id, menuTree.value);
      }

      nextTick(() => {
        isRendering.value = false;
      });
    }
  };
/** 提交按钮 */
const submitForm = (formEl: FormInstance | undefined) =>{
  if (!formEl) return
  formEl.validate(valid => {
    if (valid) {
        let companyName = ''
        companyNameList.value.forEach(item => {
          if (item.id == form.value.companyId) {
            companyName = item.name
          }
        })
       let menuIds=menuRef.value.getCheckedKeys()
       let menuIdsFu =menuRef.value.getHalfCheckedKeys()
         menuIds = menuIds.concat(menuIdsFu)
         console.log('5555555555',menuIds)
        let data = {
          companyId: form.value.companyId,
          companyName: companyName,
          name: form.value.permissionName,
          menuIds: menuIds
        }
        if(menuIds.length==0){
            ElMessage.warning("权限菜单至少选择一条");
            return false
        }
      if (typeOpen.value == 2) {
        data.id=form.value.id
        updateRolePermissions(JSON.stringify(data)).then(response => {
          cancel();
          ElMessage.success('编辑权限成功')
          getFilterData()
        });
      } else {
        addRole(JSON.stringify(data)).then(response => {
          cancel();
          ElMessage.success('新增权限成功')
          getFilterData()
      
        });
      }
    }
  });
};
//关闭弹框
const cancel = () => {
  typeOpen.value=1
  rolesRef.value.resetFields()// 重置数据
  menuRef.value.setCheckedKeys([])
  dialogUserRole.value=false
}
// 角色可选所有菜单 type:0 新增  type：1 编辑
const menuOptions=ref([])
/** 查询菜单下拉树结构 */
function getMenuList() {
  menuOptions.value = [];
  let data={
    sortBeans:[{
        field: "sort",
        isAsc: "asc",
      }]
  }
  menusList(JSON.stringify(data)).then(response => {
    let menu = handleTree(response.data, "id");
    menuOptions.value=menu
  });
}
const typeOpen=ref(1) //1新增 2编辑
// 新增权限角色弹窗
const addPermissionRoleDialog = () => {
  // 默认展开所有选择项
   typeOpen.value=1
  dialogUserRole.value = true
}
// 编辑权限
const editPermissions = (row) => {
  console.log('编辑', row)
   typeOpen.value=2
   getRoleDetail(row)
  dialogUserRole.value=true
}
//详情查询
const getRoleDetail=(row)=>{
  getRoleDetailById(row).then(res => {
   form.value.id=res.data.id
   form.value.permissionName=res.data.name
   form.value.companyId=res.data.companyId
    console.log('res',res)
    let ids=[]
    res.data.roleMenuSimpleList.forEach((item)=>{
      ids.push(item.menuId)
    })
    menuRef.value.setCheckedKeys(ids)
  })
}
//删除操作
const deleteBox = (row) => {
  ElMessageBox.confirm(
    '确认删除该条权限信息吗？',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      deleteRole(row.id).then((res) => {
        console.log('dele', res)
        ElMessage.success('权限删除成功')
      })
    })
}
// 切换状态 updateRoleStatus
const handleSwitch = (row, statu) => {
  console.log(row, statu)
  let messTitle = ''
  if (statu == '1') {
    messTitle = '该权限即将启用？'
  } else if (statu == '0') {
    messTitle = '该权限即将停用？'
  }
  ElMessageBox.confirm(
    messTitle,
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      updateRoleStatus(row, statu).then(res => {
        console.log(res)
        getFilterData()
        ElMessage.success('状态修改成功')
      }).catch(error => {
        ElMessage.warning('状态修改失败')
      })
    })
}
// 翻页控制
const pageChange = (val) => {
  getRolesPage(JSON.stringify(val)).then(res => {
    tableData.data = res.data.list.sort((a, b) => a.sort - b.sort)
    tableData.config.total = res.data.total
    console.log(res)
  })
}
</script>

<style scoped>
 .box-container{
    padding: 20px;
}
.choose-item-2 {
  margin-left: 20px;
}

.choose-item-3 {
  display: block;
  margin-left: 20px;
}
</style>